package com.android.fragmentdemo.defineviews;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.style.ReplacementSpan;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class VerticalAlignTextSpan2 extends ReplacementSpan {
    private final int textColor;
    private final float leftSpace;
    private final float rightSpace;
    private final int strokeColor;
    private final int strokeWidth;
    //num表示总共有几个ReplacementSpan
    private final int num;

    public VerticalAlignTextSpan2(int textColor, float leftSpace, float rightSpace, int strokeColor,int strokeWidth, int num) {
        this.textColor = textColor;
        this.leftSpace = leftSpace;
        this.rightSpace = rightSpace;
        this.strokeColor = strokeColor;
        this.strokeWidth = strokeWidth;
        this.num = num;
    }

    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
        return (int) (paint.measureText(text, start, end) + leftSpace + rightSpace);
    }

    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text,
                     int start, int end, float x, int top, int y,
                     int bottom, @NonNull Paint paint) {
        canvas.save();
        Paint.FontMetricsInt fontMetricsInt = paint.getFontMetricsInt();

        //使得某些字体居中显示
        paint.setColor(textColor);
        paint.setAntiAlias(true);
        paint.setDither(true);

        float offsetY = (y + fontMetricsInt.ascent + y + fontMetricsInt.descent) / 2F - (top + bottom) / 2F;
        float centerY = y - offsetY;
        canvas.drawText(text, start, end, x + leftSpace, centerY, paint);

        //绘制中划线
        paint.setColor(strokeColor);
        paint.setStrokeWidth(strokeWidth);

        float stopY = 0;
        for (int i = 1; i <= num; i++) {
            stopY += centerY / (float) Math.pow(2, i);
        }

        float endX = paint.measureText(text.toString()) * num;
        canvas.drawLine(x + leftSpace, stopY, endX, stopY, paint);

        canvas.restore();
    }
}
